package com.apes.fn.scm.commodityInquiry.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.fn.business.fixedLoss.modle.LossQuotation;
import com.apes.fn.business.fixedLoss.repository.LossQuotationRepository;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.fn.mdm.purchase.PurchasingGroupRepository;
import com.apes.fn.pi.fnCommunal.FnCommunalService;
import com.apes.fn.scm.commodityInquiry.model.CommodityInquiryItem;
import com.apes.fn.scm.commodityInquiry.model.CommodityInquiryOrder;
import com.apes.fn.scm.commodityInquiry.model.ExternalInquiry;
import com.apes.fn.scm.commodityInquiry.repository.CommodityInquiryOrderRepository;
import com.apes.fn.scm.commodityInquiry.repository.ExternalInquiryRepository;
import com.apes.fn.server.servicePlan.model.ServicePlan;
import com.apes.fn.server.servicePlan.repository.ServicePlanRepository;
import com.apes.fn.tms.repository.SiteRepository;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.logger.ApesLoggerRepository;
import com.apes.framework.jpa.logger.ApesLoggerService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.OutboxEventService;
import com.apes.framework.plugin.outbox.OutboxPayloadWrapper;
import com.apes.framework.plugin.outbox.OutboxSubscriberService;
import com.apes.framework.plugin.outbox.annotation.OutboxSubscriber;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.EventUtil;
import com.apes.framework.util.MapUtil;
import com.apes.pi.service.PiManager;
import com.apes.project.jekunAuto.report.service.ReportService;
import com.apes.scm.account.tax.model.Tax;
import com.apes.scm.masterdata.contrast.model.ContrastPartyCode;
import com.apes.scm.masterdata.contrast.repository.ContrastPartyCodeRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.party.model.Party;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.CorporateRepository;
import com.apes.scm.masterdata.party.repository.PartyRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.masterdata.product.model.ProductUom;
import com.apes.scm.masterdata.product.model.ProductUomCategory;
import com.apes.scm.masterdata.product.repository.*;
import com.apes.scm.rbac.model.User;
import com.apes.scm.rbac.repository.UserRepository;
import com.apestech.framework.json.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 商品询价单
 *
 */
@Service("commodityInquiryOrderService")
public class CommodityInquiryOrderService extends DomainService {

    @Autowired
    private PiManager piManager;

    @Autowired
    private CommodityInquiryOrderRepository commodityInquiryOrderRepository;

    @Autowired
    private ReportService reportService;
    @Autowired
    private ProductUomCategoryRepository productUomCategoryRepository;
    @Autowired
    private ProductUomRepository productUomRepository;
    @Autowired
    private CorporateRepository corporateRepository;
    @Autowired
    private CategorySupplyRangeRepository categorySupplyRangeRepository;
    @Autowired
    PartyRoleRepository partyRoleRepository;
    @Autowired
    private DeptRepository deptRepository;
    @Autowired
    private ContrastPartyCodeRepository contrastPartyCodeRepository;
    @Autowired private OutboxSubscriberService outboxSubscriberService;

    @Autowired
    private ServicePlanRepository servicePlanRepository;
    @Autowired
    private LossQuotationRepository lossQuotationRepository;
    @Autowired
    private CategoryRepository categoryRepository;
    @Autowired
    private ProductRepository productRepository;
    @Autowired
    private EnumerationRepository enumerationRepository;
    @Autowired
    private SiteRepository siteRepository;
    @Autowired
    private PurchasingGroupRepository purchasingGroupRepository;

    @Autowired
    private UserRepository userRepository;

    /********************************************操作功能START*************************************************/
    // 创建，暂时无用
    public CommodityInquiryOrder create(SimpleRequest request) {
        CommodityInquiryOrder o = request.getO(CommodityInquiryOrder.class);
        o.setCreateDate(new Date());
        o.setTimestamp(DateUtil.format(o.getCreateDate(), "yyyymmdd.hhmmss.SSS"));
        return null;

    }

    // 数据从老框架来会生成OA，同步
    public Map saveCommodityInquiryOrder(SimpleRequest simpleRequest) {
        JSONObject getJO = simpleRequest.getJO();
        CommodityInquiryOrder commodityInquiryOrder = this.formatCommodityInquiryOrder(getJO);
        CommodityInquiryOrder commodityInquiryOrder1 = commodityInquiryOrderRepository.findOne(commodityInquiryOrder.getId());
        if (commodityInquiryOrder1 != null) commodityInquiryOrder.setVersion(commodityInquiryOrder1.getVersion());
        commodityInquiryOrder.setCommodityInquiryItems(this.formatCommodityInquiryItem(commodityInquiryOrder, getJO.getJSONArray("PUR_SPXJDMX")));

        String state = commodityInquiryOrder.getState();
        List existsLoggers = SpringManager.getBean(ApesLoggerRepository.class).findAll(JpaDsl.toCriteriaByEq("businessKey", commodityInquiryOrder.getId(), "businessType", "CommodityInquiryOrder", "operate", "创建"));
        if (existsLoggers.size() == 0) this.writeLog(commodityInquiryOrder.getCreatorName().getId(), "创建", commodityInquiryOrder);
        if (commodityInquiryOrder.getReturnedPersonId() != null && state.equals("sendBack")) {
            this.writeLog(commodityInquiryOrder.getReturnedPersonId().getId(), "询价退回", commodityInquiryOrder);
        }
        if (commodityInquiryOrder.getRepurchaseId() != null && state.equals("repurchase")) {
            this.writeLog(commodityInquiryOrder.getRepurchaseId().getId(), "转采购", commodityInquiryOrder);
        }
        if (commodityInquiryOrder.getStopQuoteId() != null && state.equals("stopQuote")) {
            this.writeLog(commodityInquiryOrder.getStopQuoteId().getId(), "取消报价", commodityInquiryOrder);
        }

        commodityInquiryOrder = commodityInquiryOrderRepository.saveAndFlush(commodityInquiryOrder);
        String oldServicePlanId = "";
        if (commodityInquiryOrder.getServicePlan_id() != null) {
            oldServicePlanId = commodityInquiryOrder.getServicePlan_id().getId();
        } else {
            throw new RuntimeException("服务方案制单人不能为空");
        }
        int personnelId = SpringManager.getBean(UserRepository.class).findAll(JpaDsl.toCriteriaByEq("person.id", oldServicePlanId)).get(0).getId();
        Map map = MapUtil.mapped(commodityInquiryOrder);
        map.put("processInitiator", String.valueOf(personnelId));
        map.put("servicePlanId", String.valueOf(personnelId));
        return map;
    }

    private void writeLog(String operatorUid, String operator, CommodityInquiryOrder commdi) {
        User user = userRepository.findAll(JpaDsl.toCriteriaByEq("person.id", operatorUid)).stream().findFirst().get();
        SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                "businessType", commdi.getInnerBusinessType(),
                "businessKey", commdi.getInnerBusinessKey(),
                "operate", operator, "operator_id", user.getId()
        ));
    }

    // 数据从老框架来不生产OA，同步
/*    public void saveCommodityInquiryOrderNotOA(SimpleRequest simpleRequest) {
        JSONObject getJO = simpleRequest.getJO();
        CommodityInquiryOrder commodityInquiryOrder = this.formatCommodityInquiryOrder(getJO);
        CommodityInquiryOrder commodityInquiryOrder1 = commodityInquiryOrderRepository.findOne(commodityInquiryOrder.getId());
        if (commodityInquiryOrder1 != null) commodityInquiryOrder.setVersion(commodityInquiryOrder1.getVersion());
        commodityInquiryOrder.setCommodityInquiryItems(this.formatCommodityInquiryItem(commodityInquiryOrder, getJO.getJSONArray("PUR_SPXJDMX")));
        commodityInquiryOrder = commodityInquiryOrderRepository.saveAndFlush(commodityInquiryOrder);
    }*/

    // 同步到老框架
    public void createSynSPXJD(JSONArray param, String lydjhm) {
        System.out.println(param);
        JSONObject getData = new JSONObject();
        getData.put("ALL_DATA", param);
        outboxSubscriberService.commonSendRequest("local:CommodityInquiryOrderService.synSPXJD", "商品询价单,来源单据号码" + lydjhm, getData);
    }

    // 修改，询价单同步到老框架
    public CommodityInquiryOrder updateSpxjdService(SimpleRequest request) {
        CommodityInquiryOrder commodityInquiryOrder = request.getO(CommodityInquiryOrder.class);
        JSONObject data = this.formatNewInsuranceCompany(commodityInquiryOrder);
        JSONArray itemArray = new JSONArray();
        JSONObject param = new JSONObject();
        param.put("XJDH", commodityInquiryOrder.getId());

        JSONObject mainSPXJD_Obj = piManager.synErp("spxjdService.querySourceNewFrameData", param);
        data = JSONObject.parseObject(mainSPXJD_Obj.get("obj").toString());

        commodityInquiryOrder.getCommodityInquiryItems().forEach(commodityInquiryItem -> {
            JSONObject result = new JSONObject();
            result = this.formatSPXJDMX(result,commodityInquiryItem);
            itemArray.add(result);
        });
        data.put("CZY", this.getSession(request).getUserName());
        data.put("BZ", commodityInquiryOrder.getNote());
        data.put("JDBZ", commodityInquiryOrder.getBaseNote());
        data.put("DJLXID", "SX0");
        data.put("DJLXMC", "商品询价单");
        data.put("PUR_SPXJDMX", itemArray);
        data.remove("TS01");
        outboxSubscriberService.commonSendRequest("local:spxjdService.updateWCBJ", commodityInquiryOrder.getId(), data); // 需放开
//        commodityInquiryOrderRepository.saveAndFlush(commodityInquiryOrder); // 测试用，勿动
        return commodityInquiryOrder;

    }

    // 转采购
    private CommodityInquiryOrder repurchase(SimpleRequest request) {
        CommodityInquiryOrder commodityInquiryOrderGetJO = request.getO(CommodityInquiryOrder.class);
        commodityInquiryOrderGetJO.setState("repurchase");
        commodityInquiryOrderGetJO.setRepurchaseId(request.getPerson());
        commodityInquiryOrderGetJO.setRepurchaseDate(new Date());

        User user = userRepository.findAll(JpaDsl.toCriteriaByEq("person.id", commodityInquiryOrderGetJO.getRepurchaseId().getId())).stream().findFirst().get();
        commodityInquiryOrderGetJO.setUserId(user.getId() + "");

        SpringManager.getBean(ApesLoggerService.class).sendSynEvent("event:ir.logger.create", MapUtil.mapper(
                "businessType", commodityInquiryOrderGetJO.getInnerBusinessType(),
                "businessKey", commodityInquiryOrderGetJO.getInnerBusinessKey(),
                "operate", "转采购", "operator_id", user.getId() + ""
        ));
        commodityInquiryOrderRepository.saveAndFlush(commodityInquiryOrderGetJO);

        JSONObject param = new JSONObject();
        param.put("XJDH", request.get("id"));
        JSONObject mainSPXJD_Obj = piManager.synErp("spxjdService.querySourceNewFrameData", param);
        mainSPXJD_Obj = JSONObject.parseObject(mainSPXJD_Obj.get("obj").toString());
        mainSPXJD_Obj.put("DJZT", 50);
        mainSPXJD_Obj.put("F_GSID", mainSPXJD_Obj.get("GSID"));
        mainSPXJD_Obj.put("CZY", this.getSession(request).getUserName());
        mainSPXJD_Obj.put("BZ", commodityInquiryOrderGetJO.getNote());
        mainSPXJD_Obj.put("JDBZ", commodityInquiryOrderGetJO.getBaseNote());
        mainSPXJD_Obj.put("C_CDNM", "makeSPXJD");
        JSONArray spxjdmxArray = new JSONArray();
        commodityInquiryOrderGetJO.getCommodityInquiryItems().forEach(commodityInquiryItem -> {
            JSONObject spxjdmxObj = new JSONObject();
            this.formatSPXJDMX(spxjdmxObj, commodityInquiryItem);
            spxjdmxArray.add(spxjdmxObj);
        });

/*        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONArray array = mainSPXJD_Obj.getJSONArray("PUR_SPXJDMX");
        try {
            for (int i = 0; i < array.size(); i++) {
                if (array.getJSONObject(i).getString("YJSDRQ_SJ") != null)
                    array.getJSONObject(i).put("YJSDRQ_SJ", array.getJSONObject(i).getDate("YJSDRQ_SJ").toString());
            }
        } catch (Exception e) {

        }*/
        mainSPXJD_Obj.put("PUR_SPXJDMX", spxjdmxArray);
//        piManager.synErp("spxjdService.exec_Submit", mainSPXJD_Obj);
        outboxSubscriberService.commonSendRequest("local:CommodityInquiryOrderService.updateOldSPXJD_ZCG", "XJDH：" + mainSPXJD_Obj.getString("XJDH"), mainSPXJD_Obj);
        return commodityInquiryOrderGetJO;
    }

    // 推方案
    public CommodityInquiryOrder commodityInquiryPushPlan(SimpleRequest request) {
        CommodityInquiryOrder commodityInquiryOrder = request.getO(CommodityInquiryOrder.class);
        try {
            request.get("confirmMark");
        } catch (Exception e) {
            throw new RuntimeException("请点击【询价商品进行确认】");
        }
        commodityInquiryOrder.getCommodityInquiryItems().forEach(item ->{

            if (item.getDownCompanyPurchasePrice() == 0 ) {
                if ("现货".equals(item.getSupplyStatus().getDescription())) {
                    throw new RuntimeException("请选择询价商品进行确认");
                }

            }
        });

        try {
            this.updateSpxjdService(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if ( commodityInquiryOrderRepository.findOne(commodityInquiryOrder.getId()) != null ) {
            commodityInquiryOrder.setState("review");
            commodityInquiryOrder = commodityInquiryOrderRepository.saveAndFlush(commodityInquiryOrder);
        }
        return commodityInquiryOrder;
    }

    // 完成报价推送范围方案、定损
    public void getOldFrameSPXJD(SimpleRequest request) {
        if (true) return;
        JSONObject SPXJD_Obj = JSONObject.parseObject(request.getData().toString());
        SPXJD_Obj.put("sourceBusinessKey",SPXJD_Obj.getString("LYDJHM"));
        if ("servicePlan".equals(SPXJD_Obj.getString("LYDJLX"))) {
            //改成异步调用
            OutboxPayloadWrapper wrapper = new OutboxPayloadWrapper();
            wrapper.setSubscriber("servicePlan.server.finishInquiry");
            wrapper.setAggregateId("COMM" +SPXJD_Obj.getString("LYDJHM"));
            try {
                wrapper.setPayload(JSON.toJSONString(SPXJD_Obj));
            }catch (Exception e){
                throw new RuntimeException(e.getMessage());
            }
            SpringManager.getBean(OutboxEventService.class).sendSaveEvent(wrapper);
        } else if ("lossQuotation".equals(SPXJD_Obj.getString("LYDJLX"))){
            //改成异步调用
            OutboxPayloadWrapper wrapper = new OutboxPayloadWrapper();
            wrapper.setSubscriber("fn.lossQuotation.finishInquiry");
            wrapper.setAggregateId("Inquiry" +SPXJD_Obj.getString("LYDJHM")+ "Order" + SPXJD_Obj.getString("XJDH"));
            try {
                wrapper.setPayload(JSON.toJSONString(SPXJD_Obj));
            }catch (Exception e){
                throw new RuntimeException(e.getMessage());
            }
            SpringManager.getBean(OutboxEventService.class).sendSaveEvent(wrapper);
        }
    }

    // 取消报价回写服务方案
    public CommodityInquiryOrder getOldFrameZZSPXJD(SimpleRequest request) {
        CommodityInquiryOrder commodityInquiryOrder = request.getO(CommodityInquiryOrder.class);
        JSONObject oldFrameData = new JSONObject();
        oldFrameData.put("DJZT", 60);
        oldFrameData.put("CZY", this.getSession(request).getUserName());
        oldFrameData.put("XJDH", commodityInquiryOrder.getId());
        oldFrameData.put("BZ", commodityInquiryOrder.getNote());
        oldFrameData.put("JDBZ", commodityInquiryOrder.getBaseNote());
        oldFrameData.put("C_CDNM", "makeSPXJD");
        oldFrameData.put("LYDJLX", commodityInquiryOrder.getSourceBusinessType());
        oldFrameData.put("LYDJHM", commodityInquiryOrder.getSourceBusinessKey());
        oldFrameData.put("DJLXID", "SX0");

//        JSONObject qryIsXJ_Obj = piManager.synErp("spxjdService.qryIsXJ", oldFrameData);
//        boolean isFlag = qryIsXJ_Obj.getBoolean("obj");
//        if (isFlag) {
//            String topic = "";
//            if ("servicePlan".equals(commodityInquiryOrder.getSourceBusinessType())) {
//                JSONObject json = new JSONObject();
//                json.put("id",commodityInquiryOrder.getSourceBusinessKey());
//                json.put("roleId",MapUtil.mapped(getPerson(request)));
//                OutboxPayloadWrapper wrapper = new OutboxPayloadWrapper();
//                wrapper.setSubscriber("fn.servicePlan.backInquiry");
//                wrapper.setAggregateId("back" +commodityInquiryOrder.getSourceBusinessKey());
//                try {
//                    wrapper.setPayload(JSON.toJSONString(json));
//                }catch (Exception e){
//                    throw new RuntimeException(e.getMessage());
//                }
//                SpringManager.getBean(OutboxEventService.class).sendSaveEvent(wrapper);
//            } else if ("lossQuotation".equals(commodityInquiryOrder.getSourceBusinessType())) {
//                topic = "event:fn.lossQuotation.backInquiry";
//                EventUtil.sendSynEvent(this,topic, MapUtil.mapper("sourceBusinessKey",commodityInquiryOrder.getSourceBusinessKey()));
//            }
//        }

        commodityInquiryOrder.setState("stopQuote");
        commodityInquiryOrder.setStopQuoteDate(new Date());
        commodityInquiryOrder.setStopQuoteId(request.getPerson());
        commodityInquiryOrder = commodityInquiryOrderRepository.saveAndFlush(commodityInquiryOrder);

        outboxSubscriberService.commonSendRequest("local:CommodityInquiryOrderService.synSPXJDZZ", oldFrameData.getString("LYDJHM"), oldFrameData);

        return commodityInquiryOrder;
    }

    // 老系统终止
    public void exec_zz(SimpleRequest request) {
        JSONObject getJO =  request.getJO();
        CommodityInquiryOrder commodityInquiryOrder = commodityInquiryOrderRepository.findOne(getJO.getString("XJDH"));
        commodityInquiryOrder.setState("stopQuote");
        commodityInquiryOrder.setStopQuoteDate(new Date());
        commodityInquiryOrder.setStopQuoteId(partyRoleRepository.findOne("system"));
        commodityInquiryOrderRepository.saveAndFlush(commodityInquiryOrder);
    }

    /********************************************操作功能END*************************************************/








    /************************************************************************格式华数据START****************************************************************/
    // 点击询价商品，询价单供应商格式转换
    private JSONObject formatCommoditySupplierItem(CommodityInquiryOrder commodityInquiryOrder, JSONArray SPXJDItem_Array) {
        JSONObject commodityInquiryItemSet = new JSONObject();
        int[] newArray = new int[SPXJDItem_Array.size()];
        List PJMCIDList = new ArrayList();
        JSONArray item1 = new JSONArray();
        JSONArray item2 = new JSONArray();
        JSONArray item3 = new JSONArray();


        int supplierId = (int)(Math.random()*900)+100; // 供应商打码

        // 转化为前端需要的数据以及封装回填数据
        for (int i = 0, iLen = SPXJDItem_Array.size(); i < iLen; i++) {
            JSONObject SPXJDItemObj = SPXJDItem_Array.getJSONObject(i);
            String SPID = SPXJDItemObj.getString("SPID");
            String PJMCID = SPXJDItemObj.getString("PJMCID");

            item2 = new JSONArray();
            item3 = new JSONArray();
            JSONObject jsonItem2 = new JSONObject();

            if (newArray[i] != 0) continue;
            if (SPXJDItemObj.getString("CPHM") != null && commodityInquiryItemSet.getString("plateNumber") == null) {
                commodityInquiryItemSet.put("carLicense", SPXJDItemObj.getString("CPHM"));
            }

            JSONObject pzmcJson = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("supplier", supplierId);

            // 将新框架询价单数据格式化成老框架数据
            this.inputData(SPXJDItemObj, jsonObject);

            jsonItem2.put("id", SPID);
            jsonItem2.put("name", SPXJDItemObj.getString("SPMC"));
            jsonItem2.put("remark",SPXJDItemObj.getString("ZY"));
            jsonItem2.put("artwork", new ArrayList<>());
            jsonItem2.put("CSID", SPXJDItemObj.getString("CSID"));
            jsonItem2.put("YSPID", SPXJDItemObj.getString("YSPID"));

            // 判断是否有地区编码
            if (SPXJDItemObj.getString("CGZID") != null) commodityInquiryItemSet.put("isArea", true);
            item3.add(jsonObject);

            // 将相同的商品放在一起，并标记哪个
            for (int j = i + 1; j < SPXJDItem_Array.size(); j++) {
                if( SPID.equals(SPXJDItem_Array.getJSONObject(j).getString("SPID")) ) {
                    JSONObject jsonItem3 = new JSONObject();

                    // 将新框架询价单数据格式化成老框架数据
                    inputData(SPXJDItem_Array.getJSONObject(j), jsonItem3);
                    jsonItem3.put("supplier", (int)(Math.random()*900)+100);
                    item3.add(jsonItem3);
                    newArray[j] = 1;
                }

            }

            // 将数据中相同的配件放在相同的同级里面
            if (PJMCIDList.indexOf(PJMCID) >= 0){
                for (int j = 0; j < item1.size(); j++) {
                    JSONObject item1Obj = item1.getJSONObject(j);
                    if (PJMCID.equals(item1Obj.getString("categoryId"))) {
                        jsonItem2.put("item", item3);
                        item1.getJSONObject(j).getJSONArray("item").add(jsonItem2);
                        break;
                    }
                }
            } else{
                jsonItem2.put("item", item3);
                item2.add(jsonItem2);

                pzmcJson.put("item", item2);
                pzmcJson.put("categoryName", SPXJDItemObj.getString("PJMC"));
                pzmcJson.put("categoryId", PJMCID);
                item1.add(pzmcJson);
                PJMCIDList.add(PJMCID);
            }

        }
        commodityInquiryItemSet.put("item", item1);
        return commodityInquiryItemSet;
    }

    // 点击询价商品，将新框架询价单数据格式化成老框架数据
    public JSONObject formatNewInsuranceCompany( CommodityInquiryOrder commodityInquiryOrder) {
        JSONObject data = new JSONObject();
        data.put("XJDH", commodityInquiryOrder.getId());
        data.put("LYDJMC",commodityInquiryOrder.getSourceName());
        data.put("LYDJLX",commodityInquiryOrder.getSourceBusinessType());
        data.put("LYDJHM",commodityInquiryOrder.getSourceBusinessKey());
        data.put("DABJ",commodityInquiryOrder.getDabj());
        data.put("CLNM",commodityInquiryOrder.getVehicleCode());
        data.put("GSID",commodityInquiryOrder.getCompanyId().getId());
        data.put("GSMC",commodityInquiryOrder.getCompanyId().getName());
        data.put("PTID",commodityInquiryOrder.getPlatform().getId());
        data.put("PTMC",commodityInquiryOrder.getPlatform().getName());
        data.put("RYID",commodityInquiryOrder.getPersoonnelId().getId());
        data.put("RYMC",commodityInquiryOrder.getPersoonnelId().getName());
        data.put("MDID",commodityInquiryOrder.getDeptId().getOrigin());
        data.put("FWMDID",commodityInquiryOrder.getServiceStoreId().getId());
        data.put("ZDR_ID",commodityInquiryOrder.getId());
        data.put("ZDRQ_SJ",commodityInquiryOrder.getCreateDate());
        data.put("TS01",commodityInquiryOrder.getTimestamp());
        data.put("SHR_ID",commodityInquiryOrder.getReviewUID());
        data.put("SHRQ_SJ",commodityInquiryOrder.getReviewDate());
        data.put("THR_ID",commodityInquiryOrder.getReturnedPersonId());
        data.put("THRQ_SJ",commodityInquiryOrder.getStopQuoteDate());
        data.put("YPPGYSBJ",commodityInquiryOrder.getMatchedSuppliersValid());
        data.put("SFMZZDBJ",commodityInquiryOrder.getMZZDBJ());
        data.put("BZ",commodityInquiryOrder.getNote());
        data.put("JDBZ",commodityInquiryOrder.getBaseNote());
        data.put("CPHM",commodityInquiryOrder.getPlateNumber().getCarLicense());
        data.put("FWMDID",commodityInquiryOrder.getServiceStoreId().getOrigin());
        data.put("FWMDMC",commodityInquiryOrder.getServiceStoreId().getName());
        data.put("PTID",commodityInquiryOrder.getPlatform().getId());
        data.put("PTMD",commodityInquiryOrder.getPlatform().getName());
        data.put("CLNM",commodityInquiryOrder.getVehicleCode());
        data.put("CJHM",commodityInquiryOrder.getPlateNumber().getVin());
        data.put("PZCXMC",commodityInquiryOrder.getPlateNumber().getCarModelLabel());
        data.put("DABJ",commodityInquiryOrder.getDabj());
        data.put("PZCXID",commodityInquiryOrder.getPlateNumber().getJekunModelCode());
        data.put("FWFAZDR", commodityInquiryOrder.getServicePlan_id().getName());

        String state = commodityInquiryOrder.getState();
        switch (state) {
            case "create":
                data.put("DJZT", 0);
            case "review":
                data.put("DJZT", 20);
            case "inquiry":
                data.put("DJZT", 30);
            case "sendBack":
                data.put("DJZT", 40);
            case "repurchase":
                data.put("DJZT", 50);
            case "stopQuote":
                data.put("DJZT", 60);
            case "pushStore":
                data.put("DJZT", 70);
        }
        return data;

    }

    // 点击询价商品，格式化数据
    public void formatNewCommodityInquiryItem(JSONObject item, JSONObject json) {
        CommodityInquiryOrder commodityInquiryOrder = new CommodityInquiryOrder();
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(json);
        List list = formatSupplierDetails(commodityInquiryOrder, jsonArray);
        if (list != null && list.size() >0) item.put("commodityInquiryItem", list.get(0));

    }

    // 点击询价商品，把老框架的商品格式化成新框架
    public void inputData(JSONObject oldData, JSONObject newData) {
        double xygscgj = oldData.getDoubleValue("XYGSCGJ");
        String gysid = oldData.getString("GYSID");
        newData.put("fitting",oldData.getString("PJMCID"));
        newData.put("summary",oldData.getString("ZY"));
        newData.put("purchaseOpinion",oldData.getString("CGYJ"));
        newData.put("supplierNotes",oldData.getString("GYSBZ"));
        newData.put("quality", oldData.getString("PZMC"));
        newData.put("price", xygscgj);
        newData.put("purchasePrices", xygscgj);
        newData.put("cusRemark", oldData.getString("CGYJ"));
        newData.put("supplierRemark", oldData.getString("GYSBZ"));
        newData.put("selectFlag", 1);
        newData.put("CSMC", oldData.getString("CSMC"));
        newData.put("saleLimit", oldData.getDoubleValue("XSXJ2"));
        newData.put("priceValidity", oldData.getDoubleValue("JGYXQ"));
        newData.put("arrivalTime", oldData.getIntValue("YJDHSC"));
        newData.put("purchasingGroupId", oldData.get("CGZID"));
        newData.put("purchasingGroupName", oldData.get("CGZMC"));
        newData.put("siteId", oldData.get("ZDID"));
        newData.put("siteName", oldData.get("ZDMC"));
        newData.put("siteShippingAddress", oldData.get("ZZZSHDZ"));

        List<Enumeration> enumerations = SpringManager.getBean(EnumerationRepository.class).findAll(JpaDsl.toCriteriaByEq("type.id", "supplyStatus", "code", oldData.getDoubleValue("HYZT")));
        newData.put("supplyStatus", enumerations.get(0));

        List<ContrastPartyCode> contrastPartyCodeList = contrastPartyCodeRepository.findAll(JpaDsl.toCriteriaByEq("gysid", gysid));
        if (contrastPartyCodeList.size() == 0) {
            throw new RuntimeException("请维护角色对照表，供应商编码：" + gysid);
        }
        List<PartyRole> partyRoleList = partyRoleRepository.findAll(JpaDsl.toCriteriaByEq("party.id", contrastPartyCodeList.get(0).getParty().getId(), "role.id", "Supplier"));
        if (partyRoleList.size() == 0) {
            throw new RuntimeException("未找到对应供应商，供应商名称：" + gysid);
        }
        newData.put("supplierId", partyRoleList.get(0));

        // 回灌数据用
        formatNewCommodityInquiryItem(newData, oldData);

//        String ADDRESS = oldData.getString("ADDRESS") != null ? oldData.getString("ADDRESS") : "";
//        String CSMC = oldData.getString("CSMC") != null ? oldData.getString("CSMC") : "";
//        newData.put("ADDRESS", "从" +  CSMC  + ADDRESS + "发货");
        int iHYZT = oldData.getInteger("HYZT");
        if (iHYZT == 0) {
            newData.put("goodsSupply", "无货");
            newData.put("goodsState", iHYZT);
        } else if (iHYZT == 1) {
            newData.put("goodsSupply", "现货");
            newData.put("goodsState", iHYZT);
        } else {
            newData.put("goodsSupply", "需订货");
            newData.put("goodsState", iHYZT);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            int yjdhsc = oldData.getInteger("YJDHSC");
            int days = yjdhsc / 24;
            int hours = yjdhsc % 24;
            String showTime = "";
            if (days != 0 && hours != 0)  showTime = days + "天" + hours + "小时";
            if (days != 0 && hours == 0)  showTime = days + "天";
            if (days == 0 && hours != 0)  showTime = hours + "小时";
            newData.put("purchaseInformation", "下单后" + showTime + "送达" + oldData.get("ZDMC"));
//            oldData.put("eta", sdf.format(oldData.getDate("YJSDRQ_SJ")));
        } catch (Exception e) {

        }
    }

    // 格式化供应商明细
    public List<CommodityInquiryItem> formatSupplierDetails(CommodityInquiryOrder commodityInquiryOrder, JSONArray SPXJDItem_Array){
        List<CommodityInquiryItem> commodityInquiryItemSet = new ArrayList<>();
        CommodityInquiryItem commodityInquiryItem = new CommodityInquiryItem();
        for (int i = 0, iLen = SPXJDItem_Array.size(); i < iLen; i++) {
            JSONObject SPXJDItem_Obj = SPXJDItem_Array.getJSONObject(i);
            commodityInquiryItem = new CommodityInquiryItem();
            commodityInquiryItem.setCommodityInquiryOrderId(commodityInquiryOrder);
            commodityInquiryItem.setDeliverables(SPXJDItem_Obj.getDoubleValue("KJHJS"));
            commodityInquiryItem.setUnitPrice(SPXJDItem_Obj.getDoubleValue("XSDJ2"));
            commodityInquiryItem.setSaleLimit(SPXJDItem_Obj.getDoubleValue("XSXJ"));
            commodityInquiryItem.setSupplierUnitPrice(SPXJDItem_Obj.getDoubleValue("XSDJ1"));
            commodityInquiryItem.setEta(SPXJDItem_Obj.getDate("YJSDRQ_SJ"));
            commodityInquiryItem.setArrivalTime(SPXJDItem_Obj.getIntValue("YJDHSC"));

            if (SPXJDItem_Obj.getString("SPID") != null) {
                commodityInquiryItem.setProductId(productRepository.findOne(SPXJDItem_Obj.getString("SPID")));
            }

            List<ProductUom> productUomList = productUomRepository.findAll(JpaDsl.toCriteriaByEq("uomCategory.id", SPXJDItem_Obj.getString("SPID"), "name", SPXJDItem_Obj.getString("JLDW")));
            if (productUomList != null && productUomList.size() != 0) {
                commodityInquiryItem.setProductUomId(productUomList.get(0));
            }
            commodityInquiryItem.setSalesVolume(commodityInquiryItem.getSalesVolume(SPXJDItem_Obj.getDoubleValue("XSSL"), commodityInquiryItem.getProductUomId()));
            commodityInquiryItem.setPurchasePrices(SPXJDItem_Obj.getDoubleValue("CGCKJ"));
            commodityInquiryItem.setDownCompanyPurchasePrice(SPXJDItem_Obj.getDoubleValue("XYGSCGJ"));
            commodityInquiryItem.setDownCompayUnitPrice(SPXJDItem_Obj.getDoubleValue("XYGSXSJ"));
            commodityInquiryItem.setPurchase4SPrice(SPXJDItem_Obj.getDoubleValue("CG4S"));
            commodityInquiryItem.setUnit4SPrice(SPXJDItem_Obj.getDoubleValue("XS4S"));
            commodityInquiryItem.setEmpoweredPurchasePrice(SPXJDItem_Obj.getDoubleValue("FNCGJ"));

            int iHYZT = SPXJDItem_Obj.getInteger("HYZT");
            Enumeration enumeration = new Enumeration();
            if (iHYZT == 0) {
                enumeration = SpringManager.getBean(EnumerationRepository.class).findByTypeAndValue("无货", "supplyStatus"); //无货
            } else if (iHYZT == 1) {
                enumeration = SpringManager.getBean(EnumerationRepository.class).findByTypeAndValue("现货", "supplyStatus");//现货
            } else {
                enumeration = SpringManager.getBean(EnumerationRepository.class).findByTypeAndValue("需订货", "supplyStatus");//需订货
            }
            commodityInquiryItem.setSupplyStatus(enumeration);
            commodityInquiryItem.setPriceValidity(SPXJDItem_Obj.getIntValue("JGYXQ"));
            List<ContrastPartyCode> contrastPartyCodeList = new ArrayList<>();
            List<PartyRole> partyRoleList = new ArrayList<>();
            if (SPXJDItem_Obj.get("GYSID") != null) {
                contrastPartyCodeList = contrastPartyCodeRepository.findAll(JpaDsl.toCriteriaByEq("gysid", SPXJDItem_Obj.getString("GYSID")));
                if (contrastPartyCodeList != null && contrastPartyCodeList.size() != 0) {
                    partyRoleList = partyRoleRepository.findAll(JpaDsl.toCriteriaByEq("party.id", contrastPartyCodeList.get(0).getParty().getId(), "role.id", "Supplier"));
                    if (partyRoleList != null && partyRoleList.size() != 0) {
                        commodityInquiryItem.setSupplierId(partyRoleList.get(0));
                    }
                }
            }
            commodityInquiryItem.setOeDescription(SPXJDItem_Obj.getString("OEMS"));
            commodityInquiryItem.setPurchaseOpinion(SPXJDItem_Obj.getString("CGYJ"));
            commodityInquiryItem.setSummary(SPXJDItem_Obj.getString("ZY"));
            commodityInquiryItem.setSupplierNotes(SPXJDItem_Obj.getString("GYSBZ"));

            if (SPXJDItem_Obj.get("GSID") != null) {
                contrastPartyCodeList = contrastPartyCodeRepository.findAll(JpaDsl.toCriteriaByEq("gsid", SPXJDItem_Obj.getString("GSID")));
                if (contrastPartyCodeList !=null && contrastPartyCodeList.size() != 0) {
                    for (int k = 0, kLen = contrastPartyCodeList.size(); k < kLen; k++) {
                        ContrastPartyCode contrastPartyCode = contrastPartyCodeList.get(k);
                        partyRoleList = partyRoleRepository.findAll(JpaDsl.toCriteriaByEq("party.id", contrastPartyCode.getParty().getId(), "role.id", "Company"));
                        if (partyRoleList.size() > 0) {
                            break;
                        }
                    }
                    if (partyRoleList != null && partyRoleList.size() != 0) {
                        commodityInquiryItem.setCompanyId(partyRoleList.get(0));
                    }
                }
            }
            commodityInquiryItem.setFitting(categoryRepository.findOne(SPXJDItem_Obj.getString("PJMCID")));

            commodityInquiryItem.setInquiryMark(SPXJDItem_Obj.getIntValue("XJBS"));
            commodityInquiryItem.setSecondaryInquiry(SPXJDItem_Obj.getIntValue("ECXJBJ"));
            commodityInquiryItem.setMapAddress(SPXJDItem_Obj.getString("mapAddress"));
            commodityInquiryItem.setPJMC(SPXJDItem_Obj.getString("PJMC"));
            commodityInquiryItem.setOriginalProductId(productRepository.findOne(SPXJDItem_Obj.getString("YSPID")));
            commodityInquiryItem.setBrandId(SpringManager.getBean(BrandRepository.class).findOne(SPXJDItem_Obj.getString("PPID")));
            commodityInquiryItem.setInquiryType(SPXJDItem_Obj.getIntValue("XJLX"));
            commodityInquiryItem.setPartCode(SPXJDItem_Obj.getString("PART_CODE"));
            commodityInquiryItem.setPartName(SPXJDItem_Obj.getString("PART_NAME"));
            commodityInquiryItem.setImageSN(SPXJDItem_Obj.getString("IMAGE_SN"));
            commodityInquiryItem.setUnTaxPrice(SPXJDItem_Obj.getDoubleValue("WSCGCKJ"));
            commodityInquiryItem.setSupplierAmt(SPXJDItem_Obj.getDoubleValue("GYSSSBL"));
            commodityInquiryItem.setSiteShippingAddress(SPXJDItem_Obj.getString("ZZZSHDZ"));
            commodityInquiryItem.setSite(siteRepository.findOne(SPXJDItem_Obj.get("ZDID") == null?"":SPXJDItem_Obj.getString("ZDID")));
            commodityInquiryItem.setPurchasingGroup(purchasingGroupRepository.findOne(SPXJDItem_Obj.get("CGZID")== null?"":SPXJDItem_Obj.getString("CGZID")));

            commodityInquiryItemSet.add(commodityInquiryItem);
        }
        return commodityInquiryItemSet;
    }

    // 老框架格式化成新框架主表
    private CommodityInquiryOrder formatCommodityInquiryOrder(JSONObject mainSPXJD_Obj) {
        String lydjlx = mainSPXJD_Obj.getString("LYDJLX");
        String lydjhm = mainSPXJD_Obj.getString("LYDJHM");
        CommodityInquiryOrder commodityInquiryOrder = new CommodityInquiryOrder();
        commodityInquiryOrder.setId(mainSPXJD_Obj.getString("XJDH"));
        commodityInquiryOrder.setSourceName(mainSPXJD_Obj.getString("LYDJMC"));
        commodityInquiryOrder.setSourceBusinessType(lydjlx);
        commodityInquiryOrder.setSourceBusinessKey(lydjhm);
        commodityInquiryOrder.setDabj(mainSPXJD_Obj.getInteger("DABJ"));

        FnCustomerExpand fnCustomerExpand = new FnCustomerExpand();
        if ("servicePlan".equals(lydjlx)) {
            ServicePlan servicePlan = servicePlanRepository.findOne(lydjhm);
            fnCustomerExpand = servicePlan.getFnCustomerExpand();
            commodityInquiryOrder.setPlateNumber(fnCustomerExpand);
        } else if ("lossQuotation".equals(lydjlx)) {
            LossQuotation lossQuotation = lossQuotationRepository.findOne(lydjhm);
            fnCustomerExpand = lossQuotation.getCustomerExpand();
            commodityInquiryOrder.setPlateNumber(fnCustomerExpand);
        }
        commodityInquiryOrder.setVehicleCode(mainSPXJD_Obj.getString("CLNM"));
        PartyRole partyRole = new PartyRole();
        partyRole.setId(mainSPXJD_Obj.getString("GSID"));
        partyRole.setName(mainSPXJD_Obj.getString("GSMC"));
        commodityInquiryOrder.setCompanyId(partyRole);

        partyRole = new PartyRole();
        partyRole.setId(mainSPXJD_Obj.getString("PTID"));
        partyRole.setName(mainSPXJD_Obj.getString("PTMC"));
        commodityInquiryOrder.setPlatform(partyRole);
        if (mainSPXJD_Obj.get("FWLXID") != null) {
            commodityInquiryOrder.setServeTypeId(SpringManager.getBean(ServeTypeRepository.class).findOne(mainSPXJD_Obj.getString("FWLXID")));
        }

        Dept dept = deptRepository.findOne(JpaDsl.toCriteriaByEq("origin", mainSPXJD_Obj.getString("MDID"))).orElseThrow(() -> new RuntimeException("未找到对应的仓库信息" + mainSPXJD_Obj.getString("MDID")));
        Dept ServiceStoreId = deptRepository.findOne(JpaDsl.toCriteriaByEq("origin", mainSPXJD_Obj.getString("FWMDID"))).orElseThrow(() -> new RuntimeException("未找到对应的仓库信息" + mainSPXJD_Obj.getString("FWMDID")));
        commodityInquiryOrder.setDeptId(dept);
        commodityInquiryOrder.setServiceStoreId(ServiceStoreId);

        if( mainSPXJD_Obj.getString("RYID") != null ) {
            commodityInquiryOrder.setPersoonnelId(partyRoleRepository.findOne(mainSPXJD_Obj.getString("RYID")));
        }

        int eDJZT =  mainSPXJD_Obj.getInteger("DJZT");
        switch (eDJZT) {
            case 0:
                commodityInquiryOrder.setState("create");
                break;
            case 20:
                commodityInquiryOrder.setState("review");
                break;
            case 30:
                commodityInquiryOrder.setState("inquiry");
                break;
            case 40:
                commodityInquiryOrder.setState("sendBack");
                break;
            case 50:
                commodityInquiryOrder.setState("repurchase");
                if (mainSPXJD_Obj.getString("ZCGR_ID") != null) {
                    commodityInquiryOrder.setRepurchaseId(partyRoleRepository.findOne(mainSPXJD_Obj.getString("ZCGR_ID")));
                    commodityInquiryOrder.setRepurchaseDate(mainSPXJD_Obj.getDate("ZCGRQ_SJ"));
                }
                break;
            case 60:
                commodityInquiryOrder.setState("stopQuote");
                break;
            case 70:
                commodityInquiryOrder.setState("pushStore");
                if (mainSPXJD_Obj.getString("TSMDR") != null) {
                    commodityInquiryOrder.setPushStoreUid(partyRoleRepository.findOne(mainSPXJD_Obj.getString("TSMDR_ID")));
                    commodityInquiryOrder.setPushStoreDate(mainSPXJD_Obj.getDate("TSMDRQ_SJ"));
                }
                break;
        }

   /*     if (mainSPXJD_Obj.get("ZDR") != null && eDJZT != 0) {
            List<Party> obtainEmployees = SpringManager.getBean(PartyRepository.class).findByRoleIdAnAndName("Employee", mainSPXJD_Obj.getString("ZDR"));
            commodityInquiryOrder.setCreatorName(obtainEmployees.get(0).getPartyRoles().stream().findFirst().orElse(null));
        }*/
        commodityInquiryOrder.setCreateDate(("SYSDATE".equals(mainSPXJD_Obj.getString("ZDRQ_SJ")) || mainSPXJD_Obj.getDate("ZDRQ_SJ") == null)?new Date():mainSPXJD_Obj.getDate("ZDRQ_SJ"));

        String timestamp = mainSPXJD_Obj.getString("TS01");
        commodityInquiryOrder.setTimestamp("TIMESTAMP".equals(timestamp)?DateUtil.format(new Date(), "yyyyMMdd.hhmmss.SSS"):timestamp);
        if (mainSPXJD_Obj.getString("SHR_ID") != null) {
            commodityInquiryOrder.setReviewUID(partyRoleRepository.findOne(mainSPXJD_Obj.getString("SHR_ID")));
            commodityInquiryOrder.setReviewDate(mainSPXJD_Obj.getDate("SHRQ_SJ"));
        }

        if (mainSPXJD_Obj.getString("THR") != null) {
            List<Party> thrPartyRole = SpringManager.getBean(PartyRepository.class).findByRoleIdAnAndName("Employee", mainSPXJD_Obj.getString("THR"));
            commodityInquiryOrder.setReturnedPersonId(thrPartyRole.get(0).getPartyRoles().stream().filter(operator -> operator.getRole().getId().equals("Employee")).findFirst().orElse(null));
            commodityInquiryOrder.setReturnedDate("SYSDATE".equals(mainSPXJD_Obj.getString("THRQ_SJ"))? new Date():mainSPXJD_Obj.getDate("THRQ_SJ"));
            commodityInquiryOrder.setStopQuoteDate(commodityInquiryOrder.getReturnedDate());
            commodityInquiryOrder.setTimestamp(mainSPXJD_Obj.getString("TS01"));
        }

        commodityInquiryOrder.setMatchedSuppliersValid(mainSPXJD_Obj.getInteger("YPPGYSBJ"));
        commodityInquiryOrder.setMZZDBJ(mainSPXJD_Obj.getInteger("SFMZZDBJ"));
        commodityInquiryOrder.setNote(mainSPXJD_Obj.getString("BZ"));
        commodityInquiryOrder.setBaseNote(mainSPXJD_Obj.getString("JDBZ"));
        if (mainSPXJD_Obj.getString("ZDR") != null) {
            List<Party> obtainEmployees = SpringManager.getBean(PartyRepository.class).findByRoleIdAnAndName("Employee", mainSPXJD_Obj.getString("ZDR"));
            commodityInquiryOrder.setCreatorName(obtainEmployees.get(0).getPartyRoles().stream().filter(operator -> operator.getRole().getId().equals("Employee")).findFirst().orElse(null));
        }
        if ((mainSPXJD_Obj.get("FWFAZDR_ID") != null && !StringUtils.isEmpty(mainSPXJD_Obj.getString("FWFAZDR_ID"))) || !StringUtils.isEmpty(mainSPXJD_Obj.getString("FWFAZDR"))) {
            List<Party> obtainEmployees = SpringManager.getBean(PartyRepository.class).findByRoleIdAnAndName("Employee", mainSPXJD_Obj.getString("FWFAZDR"));
            if (obtainEmployees.size() != 0) commodityInquiryOrder.setServicePlan_id(obtainEmployees.get(0).getPartyRoles().stream().filter(operator -> operator.getRole().getId().equals("Employee")).findFirst().orElse(null));
        }

        commodityInquiryOrder.setInnerBusinessType("CommodityInquiryOrder");
        return commodityInquiryOrder;
    }

    // 老框架格式化成新框架明细
    private List<CommodityInquiryItem> formatCommodityInquiryItem(CommodityInquiryOrder commodityInquiryOrder, JSONArray SPXJDItem_Array) {
        List<CommodityInquiryItem> commodityInquiryItemSet = new ArrayList<>();
        CommodityInquiryItem commodityInquiryItem = new CommodityInquiryItem();
        Product product = new Product();
        Tax tax = new Tax();
        ProductUomCategory productUomCategory = new ProductUomCategory();
        for (int i = 0, iLen = SPXJDItem_Array.size(); i < iLen; i++) {
            JSONObject SPXJDItem_Obj = SPXJDItem_Array.getJSONObject(i);
            commodityInquiryItem = new CommodityInquiryItem();
            product = new Product();
            commodityInquiryItem.setCommodityInquiryOrderId(commodityInquiryOrder);
            commodityInquiryItem.setSalesVolume(SPXJDItem_Obj.getDoubleValue("XSSL"));
            commodityInquiryItem.setDeliverables(SPXJDItem_Obj.getDoubleValue("KJHJS"));
            commodityInquiryItem.setUnitPrice(SPXJDItem_Obj.getDoubleValue("XSDJ"));
            commodityInquiryItem.setSaleLimit(SPXJDItem_Obj.getDoubleValue("XSXJ"));
            commodityInquiryItem.setSupplierUnitPrice(SPXJDItem_Obj.getDoubleValue("XSDJ1"));
            commodityInquiryItem.setEta(SPXJDItem_Obj.getDate("YJSDRQ_SJ"));

            tax = new Tax();
            product.setTax(this.formatTax(SPXJDItem_Obj, tax));

            product.setId(SPXJDItem_Obj.getString("SPID"));
            product.setName(SPXJDItem_Obj.getString("SPMC"));
            commodityInquiryItem.setProductId(product);

            List<ProductUom> productUomList = productUomRepository.findAll(JpaDsl.toCriteriaByEq("uomCategory.id", SPXJDItem_Obj.getString("SPID"), "name", SPXJDItem_Obj.getString("JLDW")));
            if (productUomList.size() == 0) {
                throw new RuntimeException("请检查计量单位！商品编码：" + SPXJDItem_Obj.getString("SPID"));
            }

            commodityInquiryItem.setProductUomId(productUomList.get(0));

            commodityInquiryItem.setUnTaxPrice(SPXJDItem_Obj.getDoubleValue("WSCGCKJ"));
            commodityInquiryItem.setSupplierAmt(SPXJDItem_Obj.getDoubleValue("GYSSSBL"));
            commodityInquiryItem.setPurchasePrices(SPXJDItem_Obj.getDoubleValue("CGDJ"));
            commodityInquiryItem.setDownCompanyPurchasePrice(SPXJDItem_Obj.getDoubleValue("XYGSCGJ"));
            commodityInquiryItem.setDownCompayUnitPrice(SPXJDItem_Obj.getDoubleValue("XYGSXSJ"));
            commodityInquiryItem.setPurchase4SPrice(SPXJDItem_Obj.getDoubleValue("CG4S"));
            commodityInquiryItem.setUnit4SPrice(SPXJDItem_Obj.getDoubleValue("XS4S"));
            commodityInquiryItem.setEmpoweredPurchasePrice(SPXJDItem_Obj.getDoubleValue("FNCGJ"));

            int iHYZT = SPXJDItem_Obj.getInteger("HYZT");
            Enumeration enumeration = new Enumeration();
            if (iHYZT == 0) {
                enumeration = SpringManager.getBean(EnumerationRepository.class).findByTypeAndValue("无货", "supplyStatus");
            } else if (iHYZT == 1) {
                enumeration = SpringManager.getBean(EnumerationRepository.class).findByTypeAndValue("现货", "supplyStatus");
            } else {
                enumeration = SpringManager.getBean(EnumerationRepository.class).findByTypeAndValue("需订货", "supplyStatus");
            }
            commodityInquiryItem.setSupplyStatus(enumeration);
            commodityInquiryItem.setPriceValidity(SPXJDItem_Obj.getIntValue("JGYXQ"));
            List<ContrastPartyCode> contrastPartyCodeList = new ArrayList<>();
            List<PartyRole> partyRoleList = new ArrayList<>();
            if (SPXJDItem_Obj.get("GYSID") != null && !StringUtils.isEmpty(SPXJDItem_Obj.get("GYSID"))) {
                contrastPartyCodeList = contrastPartyCodeRepository.findAll(JpaDsl.toCriteriaByEq("gysid", SPXJDItem_Obj.getString("GYSID")));
                if (contrastPartyCodeList.size() == 0) {
                    throw new RuntimeException("请维护角色对照表，供应商编码：" + SPXJDItem_Obj.getString("GYSID"));
                }
                partyRoleList = partyRoleRepository.findAll(JpaDsl.toCriteriaByEq("party.id", contrastPartyCodeList.get(0).getParty().getId(), "role.id", "Supplier"));
                if (partyRoleList.size() == 0) {
                    throw new RuntimeException("未找到对应供应商，供应商名称：" + SPXJDItem_Obj.getString("GYSMC"));

                }
                commodityInquiryItem.setSupplierId(partyRoleList.get(0));
            }
            commodityInquiryItem.setOeDescription(SPXJDItem_Obj.getString("OEMS"));
            commodityInquiryItem.setPurchaseOpinion(SPXJDItem_Obj.getString("CGYJ"));
            commodityInquiryItem.setSummary(SPXJDItem_Obj.getString("ZY"));
            commodityInquiryItem.setSupplierNotes(SPXJDItem_Obj.getString("GYSBZ"));

            if (SPXJDItem_Obj.get("GSID") == null) throw new RuntimeException("公司不能为空！");
            contrastPartyCodeList = contrastPartyCodeRepository.findAll(JpaDsl.toCriteriaByEq("gsid", SPXJDItem_Obj.getString("GSID")));
            if (contrastPartyCodeList.size() == 0) {
                throw new RuntimeException("请维护角色对照表，公司编码：" + SPXJDItem_Obj.getString("GSID"));
            }
            for (int k = 0, kLen = contrastPartyCodeList.size(); k < kLen; k++) {
                ContrastPartyCode contrastPartyCode = contrastPartyCodeList.get(k);
                partyRoleList = partyRoleRepository.findAll(JpaDsl.toCriteriaByEq("party.id", contrastPartyCode.getParty().getId(), "role.id", "Company"));
                if (partyRoleList.size() > 0) {
                    break;
                }
            }
            if (partyRoleList.size() == 0) {
                throw new RuntimeException("未找到对应公司，公司：" + SPXJDItem_Obj.getString("GSMC"));
            }
            commodityInquiryItem.setCompanyId(partyRoleList.get(0));
            commodityInquiryItem.setInquiryMark(SPXJDItem_Obj.getIntValue("XJBS"));
            commodityInquiryItem.setSecondaryInquiry(SPXJDItem_Obj.getIntValue("ECXJBJ"));
            commodityInquiryItem.setMapAddress(SPXJDItem_Obj.getString("mapAddress"));
            commodityInquiryItem.setPJMC(SPXJDItem_Obj.getString("PJMC"));
            commodityInquiryItem.setFitting(categoryRepository.findOne(SPXJDItem_Obj.getString("PJMCID")));
            commodityInquiryItem.setSiteShippingAddress(SPXJDItem_Obj.getString("ZZZSHDZ"));
            commodityInquiryItem.setSite(siteRepository.findOne(SPXJDItem_Obj.get("ZDID") == null?"":SPXJDItem_Obj.getString("ZDID")));
            commodityInquiryItem.setPurchasingGroup(purchasingGroupRepository.findOne(SPXJDItem_Obj.get("CGZID")== null?"":SPXJDItem_Obj.getString("CGZID")));

            product = new Product();
            product.setId(SPXJDItem_Obj.getString("YSPID"));
            product.setName(SPXJDItem_Obj.getString("YSPMC"));
            commodityInquiryItem.setOriginalProductId(product);
            commodityInquiryItemSet.add(commodityInquiryItem);
        }
        return commodityInquiryItemSet;
    }

    // 格式化税率
    private Tax formatTax(JSONObject SPXJDItem_Obj, Tax tax) {
        String iSSLBID = SPXJDItem_Obj.getString("SSLBID");
        String iSSLBMC = SPXJDItem_Obj.getString("SSLBMC");
        if ("J0".equals(iSSLBID)) {
            tax.setId((long)5);
            tax.setName(iSSLBMC);
            tax.setAmt(SPXJDItem_Obj.getDoubleValue("AMT"));
        } else if ("J10".equals(iSSLBID)) {
            tax.setId((long)2);
            tax.setName(iSSLBMC);
            tax.setAmt(SPXJDItem_Obj.getDoubleValue("AMT"));
        } else if ("J4".equals(iSSLBID)) {
            tax.setId((long)4);
            tax.setName(iSSLBMC);
            tax.setAmt(SPXJDItem_Obj.getDoubleValue("AMT"));
        } else if ("J8".equals(iSSLBID)) {
            tax.setId((long)3);
            tax.setName(iSSLBMC);
            tax.setAmt(SPXJDItem_Obj.getDoubleValue("AMT"));
        }  else if ("J5".equals(iSSLBID)) {
            tax.setId((long)6);
            tax.setName(iSSLBMC);
            tax.setAmt(SPXJDItem_Obj.getDoubleValue("AMT"));
        } else if ("J9".equals(iSSLBID)) {
            tax.setId((long) 1);
            tax.setName(iSSLBMC);
            tax.setAmt(SPXJDItem_Obj.getDoubleValue("AMT"));
        }
        return tax;
    }

    // 新增商品询价单 格式化成老框架的字段
    public JSONObject formatSPXJDMX(JSONObject SPXJDItem_Obj, CommodityInquiryItem commodityInquiryItems) {
        SPXJDItem_Obj.put("SPID", commodityInquiryItems.getProductId().getId());
        SPXJDItem_Obj.put("SPMC", commodityInquiryItems.getProductId().getName());
        SPXJDItem_Obj.put("SPZID", commodityInquiryItems.getProductId().getProductGroup().getId());
        SPXJDItem_Obj.put("SPZMC", commodityInquiryItems.getProductId().getProductGroup().getName());
        if (Optional.ofNullable(commodityInquiryItems.getFitting()).isPresent()) {
            SPXJDItem_Obj.put("PJMCID", commodityInquiryItems.getFitting().getId());
            SPXJDItem_Obj.put("PJMC", commodityInquiryItems.getFitting().getName());
        }

        // 零件码（oem） 图号
        SPXJDItem_Obj.put("PART_CODE", commodityInquiryItems.getPartCode());
        SPXJDItem_Obj.put("PART_NAME", commodityInquiryItems.getPartName());
        SPXJDItem_Obj.put("IMAGE_SN", commodityInquiryItems.getImageSN());

        SPXJDItem_Obj.put("GYSBZ", commodityInquiryItems.getSupplierNotes());
        SPXJDItem_Obj.put("JLDW", commodityInquiryItems.getProductId().getUom().getName());
        SPXJDItem_Obj.put("DWLB", commodityInquiryItems.getProductUomId().getUomCategory().getId());
        SPXJDItem_Obj.put("YSPID", commodityInquiryItems.getOriginalProductId().getId());
        SPXJDItem_Obj.put("YSPMC", commodityInquiryItems.getOriginalProductId().getName());
        SPXJDItem_Obj.put("XSJS", commodityInquiryItems.getSalesVolume());
        SPXJDItem_Obj.put("XSSL", commodityInquiryItems.getSalesVolume());
        SPXJDItem_Obj.put("KJHJS", commodityInquiryItems.getDeliverables());
        SPXJDItem_Obj.put("CGDJ", commodityInquiryItems.getPurchasePrices());
        SPXJDItem_Obj.put("XSDJ", commodityInquiryItems.getUnitPrice());
        SPXJDItem_Obj.put("XSXJ", commodityInquiryItems.getSaleLimit());
        SPXJDItem_Obj.put("XSDJ1", commodityInquiryItems.getSupplierUnitPrice());
        SPXJDItem_Obj.put("XYGSCGJ", commodityInquiryItems.getDownCompanyPurchasePrice());
        SPXJDItem_Obj.put("XYGSXSJ", commodityInquiryItems.getDownCompayUnitPrice());
        SPXJDItem_Obj.put("CG4S", commodityInquiryItems.getPurchase4SPrice());
        SPXJDItem_Obj.put("XS4S", commodityInquiryItems.getUnit4SPrice());
        SPXJDItem_Obj.put("FNCGJ", 0);
        SPXJDItem_Obj.put("HYZT", commodityInquiryItems.getSupplyStatus() == null?0:commodityInquiryItems.getSupplyStatus().getCode());
        SPXJDItem_Obj.put("JGYXQ", commodityInquiryItems.getPriceValidity());
        if (commodityInquiryItems.getSupplierId() != null) {
            List<ContrastPartyCode> contrastPartyCodeList = contrastPartyCodeRepository.findAll(JpaDsl.toCriteriaByEq("party.id", commodityInquiryItems.getSupplierId().getParty().getId()));
            if (contrastPartyCodeList.size() > 0) SPXJDItem_Obj.put("GYSID", contrastPartyCodeList.get(0).getGysid());
        }
        SPXJDItem_Obj.put("OEMS", commodityInquiryItems.getOeDescription());
        SPXJDItem_Obj.put("CGYJ", commodityInquiryItems.getPurchaseOpinion() == null ?"" : commodityInquiryItems.getPurchaseOpinion());
        SPXJDItem_Obj.put("ZY", commodityInquiryItems.getSummary());
        SPXJDItem_Obj.put("GSID", commodityInquiryItems.getCompanyId().getId());
        SPXJDItem_Obj.put("XJBS", commodityInquiryItems.getInquiryMark());
        SPXJDItem_Obj.put("ECXJBJ", commodityInquiryItems.getSecondaryInquiry());
        SPXJDItem_Obj.put("XJLX", commodityInquiryItems.getInquiryType());
        SPXJDItem_Obj.put("mapAddress", commodityInquiryItems.getMapAddress());
        SPXJDItem_Obj.put("PLID", commodityInquiryItems.getProductId().getClassify().getId());
        SPXJDItem_Obj.put("PLMC", commodityInquiryItems.getProductId().getClassify().getName());
        SPXJDItem_Obj.put("HSBL", commodityInquiryItems.getProductId().getUom().getFactor());
        SPXJDItem_Obj.put("YJDHSC", commodityInquiryItems.getArrivalTime());
        SPXJDItem_Obj.put("WSCGCKJ", commodityInquiryItems.getUnTaxPrice());
        SPXJDItem_Obj.put("GYSSSBL", commodityInquiryItems.getSupplierAmt());
        if (commodityInquiryItems.getSite() != null) {
            SPXJDItem_Obj.put("ZDID", commodityInquiryItems.getSite().getId());
            SPXJDItem_Obj.put("ZDMC", commodityInquiryItems.getSite().getName());
        }
        if (commodityInquiryItems.getPurchasingGroup() != null) {
            SPXJDItem_Obj.put("CGZID", commodityInquiryItems.getPurchasingGroup().getId());
            SPXJDItem_Obj.put("CGZMC", commodityInquiryItems.getPurchasingGroup().getName());
        }

        SPXJDItem_Obj.put("ZZZSHDZ", commodityInquiryItems.getSiteShippingAddress());
        if ((commodityInquiryItems.getProductId().getTax() == null) ||
                (commodityInquiryItems.getProductId().getTax() != null && commodityInquiryItems.getProductId().getTax().getAmt() == 0)) {
            SPXJDItem_Obj.put("SSBL", 0);
        } /*else if (commodityInquiryItems.getProductId().getTax() != null && commodityInquiryItems.getProductId().getTax().getAmt() == 0) {
            SPXJDItem_Obj.put("SSBL", 0);
        }*/ else if (commodityInquiryItems.getProductId().getTax() != null && commodityInquiryItems.getProductId().getTax().getAmt() > 0) {
            SPXJDItem_Obj.put("SSBL", commodityInquiryItems.getProductId().getTax().getAmt() / 100);
        }
        SPXJDItem_Obj.put("FXTTJBJ", 0);
        SPXJDItem_Obj.put("BXDSDJ", 0);
        return SPXJDItem_Obj;
    }


    /************************************************************************格式华数据END****************************************************************/

















    /**********************************查询相关START*********************************************************************************************/
    // 获取车辆信息
    public JSONObject queryFnCustomerExpand(SimpleRequest simpleRequest) {
        JSONObject getJO = simpleRequest.getJO();
        String gLYDJLX = getJO.getString("LYDJLX");
        JSONObject returnData = new JSONObject();
        String gId = getJO.getString("id");
        if ("servicePlan".equals(gLYDJLX)) {
            ServicePlan servicePlan = servicePlanRepository.findOne(gId);
            returnData.put("carLicense", servicePlan.getFnCustomerExpand().getCarLicense());
            returnData.put("vendorCode", servicePlan.getFnCustomerExpand().getVendorCode());
        } else if ("lossQuotation".equals(gLYDJLX)) {
            LossQuotation lossQuotation = lossQuotationRepository.findOne(gId);
            returnData.put("carLicense", lossQuotation.getCustomerExpand().getCarLicense());
            returnData.put("vendorCode", lossQuotation.getCustomerExpand().getVendorCode());
        }
        return returnData;
    }


    // 查询询价单的完成报价供应商
    public JSONObject queryWCBJGysxjdmx(SimpleRequest request) {
        JSONObject object = new JSONObject();
        JSONObject jo = request.getJO();
        object.put("LYDJHM", jo.getString("id"));
        object.put("BG", 1);
        JSONObject mainSPXJD_Obj = piManager.synErp("spxjdService.queryWCBJGysxjdmx", object);
        JSONArray jsonArray = JSONArray.parseArray(mainSPXJD_Obj.getString("obj"));

        CommodityInquiryOrder commodityInquiryOrder = new CommodityInquiryOrder();
        commodityInquiryOrder.setId(jo.getString("id"));
        JSONObject json = formatCommoditySupplierItem(commodityInquiryOrder, jsonArray);
        return json;

    }

    // 提供给服务方案用，汇总配件
    public JSONObject queryPJHZ(SimpleRequest request) {
        JSONObject condition = new JSONObject();
        condition.put("LYDJHM", request.get("id"));
        JSONObject obj = piManager.synErp("spxjdService.queryPJHZ", condition);
        JSONObject returnData = JSONObject.parseObject(obj.get("obj").toString());
        returnData.put("LYDJHM", request.get("id"));

        return combineInquiry(returnData,queryExternalInquiry(request));
    }
    // 提供给服务方案列表用,传小写id
    public JSONObject webQueryPJHZ(SimpleRequest request) {
        JSONObject jo = request.getJO();
        String string = jo.getJSONObject("node").getString("ID");
        SimpleRequest simpleRequest = new SimpleRequest();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id",string);
        simpleRequest.setBody(jsonObject.toString());
        JSONObject condition = new JSONObject();
        condition.put("LYDJHM", string);
        JSONObject obj = piManager.synErp("spxjdService.queryPJHZ", condition);
        JSONObject returnData = JSONObject.parseObject(obj.get("obj").toString());
        returnData.put("LYDJHM", string);

        return combineInquiry(returnData,queryExternalInquiry(simpleRequest));
    }

    // 服务方案点击详情跳转询价单
    public CommodityInquiryOrder webCommodiInquiryOrder(SimpleRequest simpleRequest) {
        JSONObject obj = simpleRequest.getJO();
        JSONObject param = new JSONObject();
        param.put("XJDH", obj.get("id"));
        if (obj.get("id") == null && obj.get("XJDH") != null && !obj.getString("XJDH").equals("")) {
            param.put("XJDH", obj.get("XJDH"));
        }
        return commodityInquiryOrderRepository.findOne(param.getString("XJDH"));
    }

    /**
     * 获取询价池的演示数据
     * @param request
     * @return
     */
    public Object getInquiryPoolDemo(SimpleRequest request) {
        Map map = new HashMap();
        map.put("1",1);
        Map cache = new HashMap();
        JSONObject jsonObject = piManager.synErp("spxjdzxbService.getInquiryPoolDemo", map);
        JSONArray inquiryPoolDemoArray = jsonObject.getJSONArray("obj");
        String random = String.valueOf(Math.random());
        for (Object o : inquiryPoolDemoArray) {
            for (Object carData : ((JSONObject) o).getJSONArray("carList")) {
                JSONArray demoItem = ((JSONObject) carData).getJSONArray("inquiryPoolDemoItem");
                Map<String, List<Object>> collect = demoItem.stream().collect(Collectors.groupingBy(o1 -> {
                    JSONObject json = (JSONObject) o1;
                    return json.getString("YSPID");
                }));

                Map inquiryPool = BuildCommodityData.createBuildCommodityData().buildInquiryPool(collect, cache, random, "123",request);
                ((JSONObject) carData).put("inquiryPoolDemoItem", inquiryPool);
            }
        }
        return inquiryPoolDemoArray;
    }

    // 获取询价池的数据
    public Map getInquiryPool(SimpleRequest request) {
        JSONObject jo = request.getJO();
        String plan = jo.getString("plan");
        if ("XJBLQ".equals(plan)) {
            // 获取询价保留期数据
            Map inquiryPool = MapUtil.mapper("item2", getErpInquiryPoolData(request).get("item"));

            jo.remove("plan");
            inquiryPool.put("item",getErpInquiryPoolData(request).get("item"));

            return inquiryPool;
        } else  {
            return getErpInquiryPoolData(request);
        }
    }

    // 获取询价供应商报价比例
    public JSONObject getQuotationRatio(SimpleRequest request) {
        JSONObject condition = new JSONObject();
        JSONObject jo = request.getJO();
        String deptId = "";
        String id = jo.getString("id");
        String orderType = jo.getString("orderTypeTemp");
        if (id == null&&orderType==null) throw new RuntimeException("单号不允许为空");
        condition.put("LYDJHM", id);
        if ("ServicePlan".equals(jo.getString("innerBusinessType"))||"服务方案".equals(orderType)) {
            condition.put("CJHM", jo.getJSONObject("fnCustomerExpandTemp").getString("vin"));
            deptId = jo.getJSONObject("serviceDept").getString("id");
        } else {
            condition.put("CJHM", jo.getJSONObject("customerCar").getString("vin"));
            deptId = jo.getJSONObject("fixedLossDept").getString("id");
        }
        Dept dept = SpringManager.getBean(DeptRepository.class).findOne(deptId);
        PartyRole platform = SpringManager.getBean(FnCommunalService.class).getPlatform(false,true, dept);
        condition.put("MDID", dept.getOrigin());
        condition.put("PTID", platform.getId());
        List<Map> maps = SpringManager.getBean(PurchasingGroupRepository.class).accordingToDeptGetPurchasingGroup(deptId);
        if (maps== null || maps.size() == 0)
            throw new RuntimeException("当前部门未设置采购组，请联系中转站维护！");
        condition.put("CGZ", maps);
        return piManager.synErp("spxjdService.getQuotationRatio", condition).getJSONObject("obj");
    }

    // 获取供应商报价情况
    public JSONObject getSupplierQuotation(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        Map newFilters = new HashMap();
        for (Map filter : filters) {
            if ("CREATE_DAY".equals(filter.get("field")) && "GTE".equals(filter.get("operator")))
                newFilters.put("DAY_START_DATE", filter.get("value"));
            if ("CREATE_DAY".equals(filter.get("field")) && "LTE".equals(filter.get("operator")))
                newFilters.put("DAY_END_DATE", filter.get("value"));
            if ("CREATE_MONTH".equals(filter.get("field")) && "GTE".equals(filter.get("operator")))
                newFilters.put("MONTH_START_DATE", filter.get("value"));
            if ("CREATE_MONTH".equals(filter.get("field")) && "LTE".equals(filter.get("operator")))
                newFilters.put("MONTH_END_DATE", filter.get("value"));
            if ("TYPE".equals(filter.get("field")))
                newFilters.put("TYPE", filter.get("value"));
        }
        if ("0".equals(newFilters.get("TYPE"))) {
            if (newFilters.get("DAY_START_DATE") == null) throw new RuntimeException("日期不允许为空");
            newFilters.put("START_DATE", newFilters.get("DAY_START_DATE"));
            newFilters.put("END_DATE", newFilters.get("DAY_END_DATE"));
        } else {
            if (newFilters.get("MONTH_START_DATE") == null) throw new RuntimeException("日期不允许为空");
            newFilters.put("START_DATE", newFilters.get("MONTH_START_DATE"));
            newFilters.put("END_DATE", newFilters.get("MONTH_END_DATE"));
        }
        newFilters.put("SIZE", request.get("size"));
        newFilters.put("PAGE", request.get("page"));
        JSONArray jsonArray = piManager.synErp("spxjdzxbService.getSupplierQuotation", newFilters).getJSONArray("obj");
        JSONObject param = new JSONObject();
        for (Object o : jsonArray) {
            JSONObject jsonObject = (JSONObject)o;
            NumberFormat numberFormat = NumberFormat.getNumberInstance();
            numberFormat.setMaximumFractionDigits(2);
            double xjdl = jsonObject.getDoubleValue("XJDL");
            double khdl = jsonObject.getDoubleValue("KHDL");
            double xqmzl = jsonObject.getDoubleValue("XJXQL");

            jsonObject.put("XYL", xjdl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("XYDL") / xjdl) * 100) + '%');
            jsonObject.put("THL", xjdl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("THDL") / xjdl) * 100) + '%');
            jsonObject.put("BJL", xjdl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("BJDL") / xjdl) * 100) + '%');
            jsonObject.put("JSXYL", khdl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("JSXY") / khdl) * 100) + '%');
            jsonObject.put("CSL", khdl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("CSXY") / khdl) * 100) + '%');
            jsonObject.put("WXYL", khdl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("WXY") / khdl) * 100) + '%');
            jsonObject.put("XQMZBFB", xqmzl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("XQMZL") / xqmzl) * 100) + '%');
            jsonObject.put("XQWHL", xqmzl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("WHXQ") / xqmzl) * 100) + '%');
            jsonObject.put("XQWBJL", xqmzl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("WBJXQ") / xqmzl) * 100) + '%');

        }
        param.put("content", jsonArray);
        param.put("total", jsonArray.size() > 0 ? jsonArray.getJSONObject(0).getIntValue("TOTAL") : 0);
        param.put("pages", jsonArray.size() > 0 ? jsonArray.getJSONObject(0).getIntValue("TOTAL") / 50 : 0);
        param.put("size", 50);
        param.put("page", request.get("page"));
        param.put("elements", jsonArray.size());

        return param;
    }

    // 获取供应商报价情况明细
    public JSONObject getSupplierQuotationItem(SimpleRequest request) {
        List<Map> filters = request.get("condition");
        Map newFilters = new HashMap();
        for (Map filter : filters) {
            if ("CREATE_DAY".equals(filter.get("field")) && "GTE".equals(filter.get("operator")))
                newFilters.put("START_DATE", filter.get("value"));
            if ("CREATE_DAY".equals(filter.get("field")) && "LTE".equals(filter.get("operator")))
                newFilters.put("END_DATE", filter.get("value"));
        }

        newFilters.put("SIZE", request.get("size"));
        newFilters.put("PAGE", request.get("page"));
        JSONArray jsonArray = piManager.synErp("spxjdzxbService.getSupplierQuotationItem", newFilters).getJSONArray("obj");
        JSONObject param = new JSONObject();
        for (Object o : jsonArray) {
            JSONObject jsonObject = (JSONObject)o;
            NumberFormat numberFormat = NumberFormat.getNumberInstance();
            numberFormat.setMaximumFractionDigits(2);
            double xjdl = jsonObject.getDoubleValue("XJDL");
            double khdl = jsonObject.getDoubleValue("KHDL");
            double xqmzl = jsonObject.getDoubleValue("XJXQL");

            jsonObject.put("XYL", xjdl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("XJDL") / xjdl) * 100) + '%');
            jsonObject.put("THL", xjdl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("THDL") / xjdl) * 100) + '%');
            jsonObject.put("BJL", xjdl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("BJDL") / xjdl) * 100) + '%');
            jsonObject.put("JSXYL", khdl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("JSXY") / khdl) * 100) + '%');
            jsonObject.put("CSL", khdl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("CSXY") / khdl) * 100) + '%');
            jsonObject.put("WXYL", khdl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("WXY") / khdl) * 100) + '%');
            jsonObject.put("XQMZL", xqmzl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("XQMZL") / xqmzl) * 100) + '%');
            jsonObject.put("XQWHL", xqmzl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("WHXQ") / xqmzl) * 100) + '%');
            jsonObject.put("XQWBJL", xqmzl == 0 ? "0.00%" : numberFormat.format((jsonObject.getDoubleValue("WBJXQ") / xqmzl) * 100) + '%');

        }
        param.put("content", jsonArray);
        param.put("total", jsonArray.size() > 0 ? jsonArray.getJSONObject(0).getIntValue("TOTAL") : 0);
        param.put("pages", jsonArray.size() > 0 ? jsonArray.getJSONObject(0).getIntValue("TOTAL") / 50 : 0);
        param.put("size", 50);
        param.put("page", request.get("page"));
        param.put("elements", jsonArray.size());

        return param;
    }

    private Map getErpInquiryPoolData(SimpleRequest request) {
        //供应商编码打码缓存池
        JSONObject jo = request.getJO();

        Map cache = new HashMap();
        JSONObject condition = BuildCommodityData.createBuildCommodityData().buildInquiryPoolRequestParam(jo);
        condition.put("plan", jo.get("plan"));
        // 获取数据
        JSONObject jsonObject1 = piManager.synErp("spxjdService.getInquiryPool", condition);
        JSONArray inquiryPoolArray = jsonObject1.getJSONArray("obj");

        //根据原商品进行分组
        Map<String, List<Object>> collect = inquiryPoolArray.stream().collect(Collectors.groupingBy(o -> {
            JSONObject jsonObject = (JSONObject) o;
            if (!jsonObject.getString("GYSMC").contains("巴图鲁")) jsonObject.remove("ZBQ");
            return jsonObject.getString("PJMC");
        }));
        String id = jo.getString("id");
        if(id==null){
            id = new Random().nextInt(89999999) + 10000000+"";
        }
        return BuildCommodityData.createBuildCommodityData().buildInquiryPool(collect, cache, id, jo.getString("platform"),request);

    }
    /**********************************查询相关END*************************************************************************************************************/










    /**********************************外采相关START******************************************************/

    /***
     * 查询外采询价单
     * 询价中/询价退回/询价完成
     */
    private JSONObject queryExternalInquiry(SimpleRequest request) {
        JSONObject returnJson = new JSONObject();

        List<ExternalInquiry> externalInquiries = SpringManager.getBean(ExternalInquiryRepository.class).findAll(
                JpaDsl.toCriteriaByEq(
                        "sourceBusinessKey",  request.get("id")
                )
        );
        if (externalInquiries.size() == 0) return returnJson;

        String state =  externalInquiries.stream().max((a,b) -> {
            if (a.getLastUpdatedStamp().after(b.getLastUpdatedStamp())){
                return 1;
            } else {
                return -1;
            }
        }).get().getState();

        returnJson.put("XJZT", state.equals("approve") ? "询价完成" : state.equals("cancel") ? "询价退回" : "询价中");
        /*returnJson.put("inquiry", externalInquiries.stream().map(externalInquiry -> {
            String orderState =  externalInquiry.getState();
            return MapUtil.mapper(
                    "DJZT_CN", orderState.equals("approve") ? "完成报价" : orderState.equals("cancel") ? "退回" : "询价中",
                    "XJLX", "外部询价",
                    "ZDR", externalInquiry.get_creator().getName(),
                    "ZDRQ_SJ", DateUtil.format(externalInquiry.getCreateDate(), DateUtil.SHOW_DATETIME_FORMAT),
                    "PJHZ", externalInquiry.getExternalInquiryItems().stream().collect(Collectors.groupingBy(externalInquiryItem -> externalInquiryItem.getCategory().getId())).size(),
                    "ZHCZRQ_SJ", DateUtil.format(externalInquiry.getLastUpdatedStamp(), DateUtil.SHOW_DATETIME_FORMAT),
                    "XJDH", externalInquiry.getId(),
                    "ID", externalInquiry.getId()
            );
        }).collect(Collectors.toList()));*/
        JSONArray externalInquireiesArray = new JSONArray();
        externalInquiries.forEach(externalInquiry -> {
            String orderState =  externalInquiry.getState();
            JSONObject externalInquirieObj = new JSONObject();
            externalInquirieObj.put("DJZT_CN", orderState.equals("approve") ? "完成报价" : orderState.equals("cancel") ? "退回" : "询价中");
            externalInquirieObj.put("XJLX", "外部询价");
            externalInquirieObj.put("ZDR", externalInquiry.get_creator().getName());
            externalInquirieObj.put("ZDRQ_SJ", DateUtil.format(externalInquiry.getCreateDate(), DateUtil.SHOW_DATETIME_FORMAT));
            externalInquirieObj.put("PJHZ", externalInquiry.getExternalInquiryItems().stream().collect(Collectors.groupingBy(externalInquiryItem -> externalInquiryItem.getCategory().getId())).size());
            externalInquirieObj.put("ZHCZRQ_SJ", DateUtil.format(externalInquiry.getLastUpdatedStamp(), DateUtil.SHOW_DATETIME_FORMAT));
            externalInquirieObj.put("XJDH", externalInquiry.getId());
            externalInquirieObj.put("ID", externalInquiry.getId());
            externalInquireiesArray.add(externalInquirieObj);
        });
        returnJson.put("inquiry", externalInquireiesArray);
        return returnJson;
    }

    /**
     * 合并询价数据和外采数据
     * @param inquiry
     * @param externalInquiry
     * @return
     */
    private JSONObject combineInquiry(JSONObject inquiry, JSONObject externalInquiry) {
        List back = new ArrayList();
        List cancel = new ArrayList();
        List info = new ArrayList();
        int allInquiry=0;
        int inquiryTotal = 0;
        int quoted = 0;



        if (inquiry.get("inquiry") != null) {
            allInquiry+=inquiry.getJSONArray("inquiry").size();
            inquiry.getJSONArray("inquiry").forEach(json -> {
                JSONObject jsonObject = (JSONObject)json;
                switch (jsonObject.getString("DJZT_CN")){
                    case "新建":
                        info.add(json);
                        break;
                    case "终止报价":
                        cancel.add(json);
                        break;
                    case "退回":
                        back.add(json);
                        break;
                        default:
                            info.add(json);
                            break;
                }
                    ((JSONObject) json).put("XJLX", "内部询价");
            });
        }

        if (back.size()>0){
            inquiry.put("XJZT","询价退回");
        }else if(allInquiry==cancel.size()&&cancel.size()!=0){
            inquiry.put("XJZT","取消报价");
        }else if(inquiry.getString("LYDJHM")!=null){
            if (inquiry.getString("LYDJHM").startsWith("DS")){
                LossQuotation lossQuotation = SpringManager.getBean(LossQuotationRepository.class).findOne(inquiry.getString("LYDJHM"));
                JSONObject inquiryPool = this.invoke("commodityInquiry.order.getQuotationRatio", JSONObject.parseObject(JSONObject.toJSONString(lossQuotation)));
                inquiryTotal +=inquiryPool.getInteger("inquiryTotal");
                quoted +=inquiryPool.getInteger("Quoted");
            }
            if (inquiry.getString("LYDJHM").startsWith("FW")){
                ServicePlan servicePlan = SpringManager.getBean(ServicePlanRepository.class).findOne(inquiry.getString("LYDJHM"));
                JSONObject inquiryPool = this.invoke("commodityInquiry.order.getQuotationRatio", JSONObject.parseObject(JSONObject.toJSONString(servicePlan)));
                inquiryTotal +=inquiryPool.getInteger("inquiryTotal");
                quoted +=inquiryPool.getInteger("Quoted");
            }
            inquiry.put("XJZT","已"+inquiryTotal+"/未"+quoted);

        }
        // 直接返回某一种类型
        if (externalInquiry.size() == 0) return inquiry;
        if (inquiry.get("inquiry") == null ) return externalInquiry;
        inquiry.getJSONArray("inquiry").addAll(externalInquiry.getJSONArray("inquiry"));

/*



        // 比较最后操作日期

        JSONObject maxItem =  (JSONObject) inquiry.getJSONArray("inquiry").stream().max((a, b) -> {
            if (((JSONObject) a).getDate("ZHCZRQ_SJ").after(((JSONObject) b).getDate("ZHCZRQ_SJ"))){
                return 1;
            } else {
                return -1;
            }
        }).orElseGet(null);

        //  处理询价状态
        if (maxItem.getString("XJDH").startsWith("WX12") ||
                maxItem.getString("XJDH").startsWith("WC12") ){
            inquiry.put("XJZT", externalInquiry.getString("XJZT"));
        }

*/
        return inquiry;
    }

    /**
     * 外采询价点击判断商品是否有询过价
     * @param request
     * @return
     */
    public List<Map> queryCommodityInquiryProduct(SimpleRequest request) {
        JSONObject getJO = request.getJO();
        List<Map> getCommodiInquieryOrders = commodityInquiryOrderRepository.queryCommodityInquiryProduct(getJO.getString("SOURCE_BUSINESS_KEY"), getJO.getString("SOURCE_BUSINESS_TYPE"), getJO.getJSONArray("PRODUCT_ID"));
        return getCommodiInquieryOrders;
    }

    /**********************************外采相关END******************************************************/












    /**********************************接口调用相关START******************************************************/
    @OutboxSubscriber(id="local:CommodityInquiryOrderService.synSPXJDZZ", name="询价单同步老框架-终止")
    private void synSPXJDZZ(OutboxPayloadWrapper outboxPayloadWrapper) {
        JSONObject resultObj = piManager.synErp("spxjdService.exec_Submit", outboxPayloadWrapper.getPayload());
    }

    @OutboxSubscriber(id="local:CommodityInquiryOrderService.synSPXJDTFA", name="询价单推方案")
    private void synSPXJDTFA(OutboxPayloadWrapper outboxPayloadWrapper) {
        JSONObject resultObj = piManager.synErp("spxjdService.exec_Submit", outboxPayloadWrapper.getPayload());
    }

    @OutboxSubscriber(id="local:CommodityInquiryOrderService.synSPXJD", name="询价单同步老框架")
    private void synSPXJD(OutboxPayloadWrapper outboxPayloadWrapper) {
        JSONObject resultObj = piManager.synErp("spxjdService.createManySPXJD", outboxPayloadWrapper.getPayload());
    }

    @OutboxSubscriber(id="local:spxjdService.updateWCBJ", name="修改商品询价单同步到老框架")
    private void updateSynSPXJD(OutboxPayloadWrapper outboxPayloadWrapper) {
        JSONObject resultObj = piManager.synErp("spxjdService.updateWCBJ", outboxPayloadWrapper.getPayload());
    }

    @OutboxSubscriber(id="local:CommodityInquiryOrderService.updateOldSPXJD_ZCG", name="询价单同步老框架-转采购")
    private void updateOldSPXJD_ZCG(OutboxPayloadWrapper outboxPayloadWrapper) {
        JSONObject resultObj = piManager.synErp("spxjdService.exec_Submit", outboxPayloadWrapper.getPayload());
    }
    /**********************************接口调用相关END******************************************************/
}
